<template>
  <div class="users">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片面板 -->
    <el-card class="box-card">
      <!-- 搜索和添加区域：搜索框和添加按钮通过el-row包裹布局 -->
      <el-row :gutter="20">
        <el-col :span="7"
          ><el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            class="input-with-select"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button> </el-input
        ></el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">
            添加用户
          </el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区域：el-table表格渲染 -->
      <el-table
        :data="userList"
        style="width: 100%;margin:20px 0;"
        border
        stripe
        :header-cell-style="{
          background: '#F5F5F5',
          color: '#000',
          fontSize: '14px',
          fontWeight: '600'
        }"
      >
        <!-- 索引列type = 'index' -->
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column prop="username" label="姓名" width="100">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="mobile" label="电话" width="180">
        </el-table-column>
        <el-table-column prop="role_name" label="角色" width="100">
        </el-table-column>
        <el-table-column prop="mg_state" label="状态" width="100">
          <template slot-scope="scope">
            <!-- {{ scope.row.mg_state }} -->
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <!-- {{ scope.row.mg_state }} -->
            <el-tooltip
              effect="dark"
              content="编辑"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showEditDialog(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              effect="dark"
              content="删除"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="removeUserById(scope.row.id)"
              ></el-button>
            </el-tooltip>

            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 对话框内容 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户的对话框 -->
    <el-dialog
      title="编辑用户信息"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 对话框内容 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配用户角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @close="setRoleDialogClosed"
    >
      <!-- 对话框内容 -->
      <div class="dialog-content">
        <p>当前的用户：{{ userInfo.username }}</p>
        <p>当前的角色：{{ userInfo.role_name }}</p>
        <p>
          分配新角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <!-- 对话框底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'users',
  components: {},
  data() {
    //   验证邮箱是否格式正确
    var checkEmail = (rule, value, callback) => {
      const regEmail = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }
    //   验证手机号码是否格式正确
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^[1][3,4,5,7,8,9][0-9]{9}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号码'))
    }
    return {
      inputSearchvalue: '',
      queryInfo: {
        query: '',
        // 当前页数
        pagenum: 1,
        // 当前每页显示的数据条数
        pagesize: 5
      },
      userList: [],
      total: 0,
      //   添加用户角色对话框的显示与隐藏
      addDialogVisible: false,
      //   编辑用户角色对话框的显示与隐藏
      editDialogVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addFormRules: {
        username: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editForm: {},
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      //   分配角色对话框的显示与隐藏
      setRoleDialogVisible: false,
      //   分配权限时展示的角色信息
      userInfo: {},
      //   所有角色的数据列表
      roleList: [],
      //   已选中的角色id值
      selectedRoleId: ''
    }
  },
  created() {
    this.getUserList()
  },
  mounted() {},
  methods: {
    async getUserList() {
      const result = await this.$http.get('users', {
        params: this.queryInfo
      })
      const { data: res } = result
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      //   this.$message.success(res.meta.msg)
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听pageSize改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听页码值改变
    handleCurrentChange(newPage) {
      //   console.log(`当前页: ${val}`)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 监听开关状态的变化
    async userStateChange(userInfo) {
      console.log(userInfo)
      const result = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      console.log(result)
      const { data: res } = result
      if (res.meta.status !== 200) {
        //   如果更新状态失败，需要将页面上switch返回原来的状态
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error(res.meta.msg)
      } else {
        return this.$message.success(res.meta.msg)
      }
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    //  添加用户的确定事件
    addUser() {
      //  先做添加表单的预校验操作
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.warning('请再仔细检查一下!!') // 如果校验未通过则不往下执行
        // 执行添加用户请求
        const result = await this.$http.post('users', this.addForm)
        const { data: res } = result
        // 判断返回结果是否是成功的状态码，不是则打印返回的错误信息
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        // 关闭添加对话框
        this.addDialogVisible = false
        // 刷新用户列表
        this.getUserList()
        // 成功提示
        this.$message.success('添加用户成功!')
      })
    },
    // 展示编辑用户的对话框
    async showEditDialog(id) {
      console.log(id)
      this.editDialogVisible = true
      // 查询用户信息
      const result = await this.$http.get('users/' + id)
      const { data: res } = result
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)

      this.editForm = res.data
    },
    // 监听编辑用户对话框的关闭事件：重置为了消除预校验状态的保持
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 编辑用户之后提交
    editUserInfo() {
      //  先做编辑表单的预校验操作
      this.$refs.editFormRef.validate(async valid => {
        console.log(valid)
        if (!valid) return this.$message.warning('请再仔细检查一下!!') // 如果校验未通过则不往下执行
        // 执行编辑用户提交请求
        const result = await this.$http.put('users/' + this.editForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        const { data: res } = result
        // 判断返回结果是否是成功的状态码，不是则打印返回的错误信息
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        // 关闭添加对话框
        this.editDialogVisible = false
        // 刷新用户列表
        this.getUserList()
        // 成功提示
        this.$message.success('更新用户信息成功!')
      })
    },
    // 根据id删除对应的用户信息
    async removeUserById(id) {
      // 弹框询问用户是否确认删除
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      // 点击确定，返回"confirm"
      // 点击取消，返回"cancel"
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('users/' + id)

      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success('用户删除成功！')
      // 有个bug,如果是第二页第一个数被删除，则显示为空而不是返回第一页显示
      //   因为此时仍然在空的一页，页数没变，请求就为空了，后期需要弥补
      this.getUserList()
    },
    // 分配角色
    async setRole(userInfo) {
      console.log(userInfo)
      // 打开对话框前获取用户信息，用于展示
      this.userInfo = userInfo
      //   同时获取所有角色信息用于分配新角色的下拉选择展示
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      console.log(res.data)
      // 将获取的角色信息列表保存到data的roleList中
      this.roleList = res.data
      // 展示分配角色的对话框
      this.setRoleDialogVisible = true
    },
    // 点击对话框的确定按钮，分配角色
    async saveRoleInfo() {
      // 如果没有选择新角色进行分配，则提示
      if (!this.selectedRoleId) {
        this.$message.error('请选择要分配的角色')
      }
      //
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        {
          rid: this.selectedRoleId
        }
      )
      console.log(res)
      //   如果请求出错，打印错误信息
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 请求成功则进行提示
      this.$message.success('更新角色成功！')
      // 刷新当前列表
      this.getUserList()
      // 关闭对话框
      this.setRoleDialogVisible = false
    },
    // 更新用户角色再次打开分配角色对话框，选择器中应该为空
    setRoleDialogClosed() {
      // 重置选择器
      this.selectedRoleId = ''
      this.userInfo = {}
    }
  }
}
</script>
<style lang="less" scoped>
/* @import url(); 引入公共css类 */
.el-table {
  font-size: 12px;
}

.dialog-content {
  p {
    margin-bottom: 20px;
  }
}
</style>
